<?php
// +----------------------------------------------------------------------
// | Author: 发仔 <i@fazi.me> 
// +----------------------------------------------------------------------

namespace app\manual\controller;

use think\Controller;
use think\Db;

class Index extends Base
{
    function index() {
		
		halt($_SERVER);
		
		$file = ROOT_PATH.'db.export';
		$json = file_get_contents($file);
		$tables = json_decode($json,1)['tableList'];
		
		$tables = array_column($tables,null,'tableName');
		ksort($tables);
		
//		清空
		Db::query('truncate table doc_db_map;');
		$all = [];
		foreach($tables AS $table) {
			
			$data = [
				'project_id' => 1,
				'user_id' => 1,
				'user_id' => 1,
				'table_name' => $table['tableName'],
				'table_comment' => $table['tableDesc'],
				'field_json' => [],
			];
			
			//字段
			foreach($table['fieldList'] AS $field) {
				
				$data['field_json'][] = [
					'field' => $field['fieldName'],
					'type' => $field['fieldType'],
					'is_null' => $field['isNotNull'],
					'is_pk' => $field['isPrimaryKey'],
					'comment' => $field['fieldDesc'],
					'default_value' => $field['defaultValue'],
				];
			}
			
			$data['field_json'] = json_encode($data['field_json']);
			
			$all[] = $data;
		}
		
		$rslt = Db::table('doc_db_map')->insertAll($all);
		halt($rslt);
		
	}
	
	
	public function alter() {
		
		$file = ROOT_PATH.'db.export';
		$json = file_get_contents($file);
		$tables = json_decode($json,1)['tableList'];
		
		$tables = array_column($tables,null,'tableName');
		ksort($tables);
		
//		清空
		$alter = [];
		foreach($tables AS $table) {
			foreach($table['fieldList'] AS $field) {
				$field['fieldDesc'] && $alter[]	= "ALTER TABLE `{$table['tableName']}` MODIFY COLUMN `{$field['fieldName']}` {$field['fieldType']} COMMENT '{$field['fieldDesc']}';"; 
			}
			
		}
		
		$sql = implode(PHP_EOL,$alter);
//		halt($sql);
		file_put_contents(ROOT_PATH.'comment.sql',$sql);
		
	}
	
}
